#include<stdio.h>
#include<stdbool.h>
#include<string.h>
#include<math.h>

#include"IntegralSinc.h"

double InputBorder(char *prompt);
double Sinc(double x);
double EstimateIntegral(double a, double b, int n);

int main()
{
    double a, b, pres, res, error=INF;

    a = InputBorder("Input lower boundary a:");
    b = InputBorder("Input upper boundary b:");

    int n = 10;
    pres = EstimateIntegral(a, b, n);
    printf("Epoch %d, n = %d, result = %.9lf\n", n - 9, n, pres);
    n++;
    while(n <= MAX_SIZE && error >= MIN_ERROR)
    {
        res = EstimateIntegral(a, b, n); 
        error = fabs(res - pres);
        printf("Epoch %d, n = %d, result = %.11lf, error = %lg\n", n - 9, n, res, error);
        pres = res;
        n++;
    }
    return 0;
}


double EstimateIntegral(double a, double b, int n)
{
    double val = 0;
    double delta = (b - a) / (double)n;
    for(int i=1;i<=n;i++)
    {
        val += (Sinc(a + (i - 0.5) * delta) * delta);
    }
    return val;
}

double Sinc(double x)
{
    double val = 1;
    if(x)
    {
        val = sin(M_PI * x) / (M_PI * x);
    }
    return val;
}

double InputBorder(char *prompt)
{
    char buffer[100];
    char *p = buffer;
    double val;
    do
    {
        printf("%s ", prompt);
        fgets(buffer, sizeof(buffer), stdin);
        if(strlen(buffer)>0)
            buffer[strlen(buffer)-1] = '\0';
        p = buffer;
        while(*p == ' ')p++;
        if(strlen(p) > 0 && p[0] == '.')break;
    }while(strlen(p) < 1 || p[0] < '0' || p[0] > '9');

    sscanf(p, "%lf", &val);
    return val;
} 
